package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.pojo.dto.UserInsertDTO;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * RestController注解
 *      1.组合注解,等价于@Controller+@ResponseBody
 *      2.添加此注解后,所有的控制器方法上不需要再添加 @ResponseBody 注解
 *      3.简化开发
 */
@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("注册功能")
    @ApiImplicitParam(name = "userInsertDTO", value = "用户登录信息", required = true,dataType = "UserInsertDTO")
    @PostMapping("insert")
    public String insert(UserInsertDTO userInsertDTO){
        log.debug("UserInsertDTO + "+ userInsertDTO);
        /*
            梳理业务逻辑,确定接口-假如说是注册功能:
            1.获取用户输入的数据
            2.校验用户输入的数据[暂时不做]
            3.校验用户名是否被占用[SELECT接口]
                3.1 如果被占用,提示用户名被占用
                3.2 未被占用,插入数据[INSERT接口],返回响应
         */
        User user =  new User();
        //复制属性
        BeanUtils.copyProperties(userInsertDTO,user);
        user.setCreated(new Date());
        //调用接口方法
        userMapper.insertUser(user);
        return "添加成功";
    }
    @ApiOperation("查询所有用户")
    @GetMapping("userList")
    public List<UserListVO> userList(){
        log.debug("查询所有用户信息");
        return  userMapper.selectUserList();
    }

    /**
     * 3.删除指定用广功能
     *      3.1 http: //localhost:8080/v1/users/delete?id=1
     *      3.2 http:/ /localhost:8080/v1/users/delete/3
     */
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "id", value = "用户编号", required = true,dataType = "int")
    @GetMapping("delete")
    public String delete(Integer id){
        if(id<0){
            throw new RuntimeException("id不能小于0");
        }
        log.debug("删除用户,id为"+id);
        userMapper.deleteUser(id);
        return "删除成功,id为";
    }
    @ApiOperation("修改用户信息")
    @ApiImplicitParam(name = "user", value = "用户信息", required = true,dataType = "User")
    @PostMapping("update")
    public String update(User user){
        log.debug("修改用户信息,user="+user);
        userMapper.updateUser(user);
        return "修改成功";
    }
    /**
     * 5.获取指定用户信息功能: 在Path中传递数据
     *      http://localhost:8080/v1/users/select/用户ID
     */
    @ApiOperation("查询指定用户")
    @ApiImplicitParam(name = "uid", value = "用户编号", required = true,dataType = "int")
    @GetMapping("select/{uid}")
    public User select(@PathVariable Integer uid){
        log.debug("获取指定用户信息,uid="+uid);
        return userMapper.selectUserById(uid);
    }

}
